package com.ericsson.eritask;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.ericsson.eritask.domain.User;
import com.ericsson.eritask.domain.UserProject;
import com.ericsson.eritask.dto.CommentsDTO;
import com.ericsson.eritask.dto.MyTaskDTO;
import com.ericsson.eritask.dto.ProjectDTO;
import com.ericsson.eritask.dto.ReminderDTO;
import com.ericsson.eritask.dto.TaskDTO;
import com.ericsson.eritask.dto.UserDTO;
import com.ericsson.eritask.dto.UserTaskDTO;
import com.ericsson.eritask.service.AssignTaskService;
import com.ericsson.eritask.service.CommentService;
import com.ericsson.eritask.service.MyTaskService;
import com.ericsson.eritask.service.UserService;
import com.ericsson.eritask.utility.EritaskUtility;

@Controller
public class NewTaskController {

	private static final Logger logger = LoggerFactory.getLogger(NewTaskController.class);

	@Autowired
	AssignTaskService assignTaskService;

	@Autowired
	MyTaskService myTaskService;
	
	@Autowired
	UserService userService;

	public void setMyTaskService(MyTaskService myTaskService) {
		this.myTaskService = myTaskService;
	}

	@Autowired
	CommentService commentService;

	public void setAssignTaskService(AssignTaskService assignTaskService) {
		logger.debug("In setAssignTaskService method..........");
		this.assignTaskService = assignTaskService;
	}

	@RequestMapping(value = "/NewTask", method = { RequestMethod.GET, RequestMethod.POST })
	public String Newtaskform(Map<String, Object> model) {
		logger.debug("In Newtaskform method..........");
		logger.debug("----------------------Newtaskform-----------------------");
		model.put("UserDTO", new UserDTO());
		return "NewTask";

	}

	@RequestMapping(value = "/ProcessNewtaskFormData", method = RequestMethod.POST)
	public @ResponseBody String getFormData(HttpServletRequest request, Map<String, String> map, Model model,
			@RequestParam(value = "subject",required=false) String subject, @RequestParam(value = "project",required=false) String project_name,
			@RequestParam(value = "startDate", required = false) String startDate,
			@RequestParam(value = "dueDate",required=false) String dueDate, @RequestParam(value = "staus_",required=false) String status,
			@RequestParam(value = "priority_",required=false) String priority_,
			@RequestParam(value = "percentage_",required=false) String percentage_,
			@RequestParam(value = "reminderDt",required=false) String reminderDt, @RequestParam(value = "chkbox",required=false) String checkbox,
			@RequestParam(value = "reminderTym",required=false) String reminderTym,
			@RequestParam(value = "user_signum", required = false) String[] user_signum,
			@RequestParam("files") MultipartFile[] multipartfiles, @RequestParam(value = "comments",required=false) String comments)
					throws IOException {
		System.out.println("In getFormData method..........");
		logger.debug("In getFormData method..........");
		logger.debug("----------------Create new task--------------------------------");
		List<MyTaskDTO> allTaskList = new ArrayList<MyTaskDTO>();
		System.out.println("subject fromajax call:" + subject);
		System.out.println("project:" + project_name);
		// System.out.println("project fromajax call:"+project_name);
		System.out.println("startDate:" + startDate);
		System.out.println("dueDate:" + dueDate);
		System.out.println("staus_:" + status);

		System.out.println("priority_:" + priority_);
		System.out.println("reminderDt:" + reminderDt);

		System.out.println("percentage_:" + percentage_);
		System.out.println("checkbox:" + checkbox);
		System.out.println("remTym:" + reminderTym);
		String message = "";
		EritaskUtility utility = new EritaskUtility();
		Date sDate = null;
		Date dDate = null;
		Date rDate = null;
		if (startDate != null && !"".equals(startDate)) {
			sDate = utility.stringToDate(startDate);
		}

		if (dueDate != null && !"".equals(dueDate)) {
			dDate = utility.stringToDate(dueDate);
		}
		if (reminderDt != null && !"".equals(reminderDt)) {
			rDate = utility.stringToDate(reminderDt);
		}

		// String user_signum[]= request.getParameterValues("user_signum");
		for (int i = 0; i < user_signum.length; i++) {
			System.out.println("user_signum---====+++" + user_signum[i]);
		}
		System.out.println("date format ---- Start date:" + sDate);
		TaskDTO task = new TaskDTO();
		if (subject != null) {
			task.setSubject(subject);
		}
		task.setStartDate(sDate);
		task.setDueDate(dDate);
		if (priority_ != null && !"".equals(priority_)) {
			task.setPriority(priority_);
		}
		if (checkbox != null && !"".endsWith(checkbox)) {
			task.setReminder(Boolean.valueOf(checkbox));
		}
		if (percentage_ != null && !"".equals(percentage_)) {
			task.setPercentageComplete(Integer.parseInt(percentage_));
		}
		if (status != null && !"".equals(status)) {
			task.setStatus(status);
		}
		ReminderDTO reminderDTO = new ReminderDTO();
		reminderDTO.setReminderDate(rDate);
		if (reminderTym != null && !"".equals(reminderTym)) {
			reminderDTO.setReminderTime(reminderTym);
		}

		////////////////////////////////////////////////////

		System.out.println("in uploadFiles().........");
		
		//String signum = request.getSession().getAttribute("user_signum").toString();
		 Authentication auth= SecurityContextHolder.getContext().getAuthentication();

			System.out.format("Name of the user is %s", auth.getName());
			User user = userService.findByName(auth.getName());
			String signum = user.getSignum();
		List<String> lfId = new ArrayList<String>();
		List<InputStream> files = new ArrayList<InputStream>();
		for (int i = 0; i < multipartfiles.length; i++) {
			files.add(multipartfiles[i].getInputStream());
		}

		System.out.println("signum" + signum);
		String filename = request.getContextPath().toString();
		lfId = commentService.insertDocumentFiles(files, filename);
		System.out.println("list of fileId in NewTaskController" + lfId);

		String docId = commentService.inserDocument(lfId, comments);
		System.out.println("fileId in NewtaskController::::" + docId);

		CommentsDTO commentDto = new CommentsDTO();
		commentDto.setDocId(docId);
		commentDto.setSignum(signum);
		commentDto.setCommentdate(new Date());

		commentService.insertComment(commentDto);
		////////////////////////////////////////////////

		ProjectDTO projDto = new ProjectDTO();
		System.out.println("Project Name =" + project_name);
		if (project_name != null && !"".equals(project_name)) {
			projDto.setProjectName(project_name);
		}

		UserTaskDTO userTaskDto = new UserTaskDTO();
		userTaskDto.setSignums(Arrays.asList(user_signum));
		boolean flag = false;
		try {
			// flag = assignTaskService.saveTask(projDto, task, reminderDTO);
			flag = assignTaskService.saveUserTask(projDto, task, reminderDTO, userTaskDto);
			// update data table after insert
			String user_name = request.getSession().getAttribute("user_Name").toString();
			String password = request.getSession().getAttribute("passWord").toString();

			System.out.println("u = " + user_name + " " + " p = " + password);

			List<MyTaskDTO> taskDTO = null;
			List<UserProject> userproject_list = myTaskService.getUserProjectList(user_name, password);
			if (userproject_list != null && userproject_list.size() > 0) {
				for (UserProject up : userproject_list) {

					int proj_id = up.getProject().getProjectId();
					System.out.println("proj_id in controller " + proj_id);
					taskDTO = myTaskService.populateMyTaskList(proj_id);
					allTaskList.addAll(taskDTO);
					System.out.println("taskDTO size in controller " + taskDTO.size());
					System.out.println("allTaskList size in controller " + allTaskList.size());
				}
			}
			// //end update data table after insert
		} catch (Exception e) {
			System.out.println("Do nothing");
		}
		if (flag == true) {
			message = "Data submitted succesfully";
		} else {
			message = "Exception occurred while inserting data";
		}
		map.put("message", message);

		logger.debug("task Reminder exiting the method:" + task.getReminder());

		model.addAttribute("mytaskDTO", allTaskList);
		// return "redirect:validateUser";
		return "MyTask";

	}

}
